package com.event.attention;

import com.google.common.eventbus.Subscribe;
import com.handler.email.Email;
import com.handler.email.EmailHandler;
import com.mapper.self.CompanyMapper;
import com.pojo.ShCompany;
import com.utils.JsonUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by Huoyunren on 2016-09-07.
 * 关注/取消关注消息监听器
 */
@Component
public class AttentionEventListener {
  private static final Logger LOG = LoggerFactory.getLogger(AttentionEventListener.class);

  @Autowired
  private EmailHandler emailHandler;
  @Autowired
  private CompanyMapper companyMapper;

  @Subscribe
  public void work(AttentionEvent event) {

    if (event.getIsAttention() == 0) {
      // - 取消关注不提醒
      return;
    }
    LOG.info("监听到关注行为：{}", JsonUtils.JSON().toJson(event));
    // - 发送邮件
    mailNotify(event.getEmail(),event.getAttentionEmail());
  }

  private void mailNotify(String email, String attentionEmail) {
    ShCompany company = companyMapper.queryByEmail(email.toString());
    String alias = company.getName();
    if (StringUtils.isBlank(alias)) {
      alias = email;
    }
    String subject = alias + "关注了你！";
    StringBuffer content = new StringBuffer();
    content.append("恭喜.你又长粉啦！\n");
    content.append("来自刘员外用户："+alias+"关注了你.");
    content.append("付出终将有回报.再接再厉！\n");
    content.append("看看TA是谁：");
    content.append("http://liuyuanwai.cn/user/queryinfo?email=");
    content.append(email);
    String[] to = {attentionEmail};
    Email e = new Email();
    e.setEnableHtml(Boolean.FALSE);
    e.setSubject(subject);
    e.setTo(to);
    e.setContent(content.toString());
    emailHandler.asyncSendMail(e);
  }
}
